const fs = require('fs');
const path = require('path');
const readlineSync = require('readline-sync');
const mysql = require('mysql')

// 配置系统文件参数
/*sidebar 侧边栏文件地址*/   const sideBarSrc = './src/common/sidebar.vue'
/*router 路由文件地址*/     const routerIndexSrc = './src/router/index.js'
/*app 后端入口文件地址*/     const appSrc = './app.py'
/*db 数据库地址*/           const dbSrc = './controllers/db.py'
/*controllers 后端逻辑*/   const controllerSrcName = 'controllers'
/*src         前端逻辑*/   const froSrcName = 'src'
const controllerSrc = './' + controllerSrcName
const froSrc = './' + froSrcName

//数据库配置
const host = '127.0.0.1'
const user = 'root'
const password = '123456'
// const database = 'bob_event_dev'
/*database 项目数据库名称*/  const database = 'westgame_event_project_dev'

// 项目名称
/*projName 项目英文&数据库名&协议*/  const projName = 'gui_zhen'
/*database 项目中文名称*/      const projNameCh = '借鬼镇测试'
// 数据库参数
const dbObj = {
    "project": "BIGINT PRIMARY KEY AUTO_INCREMENT",
    "remark": "Text",
    "basic": "Text",
    // "`limit`": "Text",
    // "detail": "Text",
    "version": "Integer"
}
// 子页面名称 暂时不到,保留参数(add router用)
const projPages = ['inline']
// 子组件名称 ,目前不用，保留参数
const projComponents = ['comp']


const indexConfig = {
    "barFunc": ["upload", "export", "post"],
    "indexTab": {
        "barFunc": ["remark","save"],
        "form":[
            {
                "label":"方案id",
                "prop": "project",
                "width": "300px"
            },
            {
                "label":"备注",
                "prop": "remark.remark",
                "type": "input-remark",
                "width": "auto"
            },
            {
                "label":"操作",
                "type": "options",
                "width": "400px"
            },
        ]

    }
}

const detailConfig = {
    "inline":[
        {
            "label": "form模块",
            "comp_name": "from-try",
            "type": "from",
            "field": [
                {
                    "label": "ui",
                    "type": "input",
                    "key": "basic.ui",
                    "valid": ["require","number","min-0","max-10"]
                }
            ]
        },
    ]
}

//确认添加
console.log('please confirm the follow info:');
console.log('   projName        :',projName);
console.log('   projNameCh      :',projNameCh);
console.log('   database        :',database);
console.log('   control文件夹   :',controllerSrcName);
console.log('   dbSrcPath       :',dbSrc);

// let answer = readlineSync.question('have added sign ly-router and ly-sidebar . (yes/no)?:');
// // answer = 'yes'
// answer = answer.toLowerCase()
// if (answer === 'yes') {
//   console.log('executing...');
//   // 在这里编写需要执行的代码
// } else if (answer === 'no') {
//   console.log('ok, execute have quit!');
//   process.exit(10001);
// } else {
//   console.log('input err, execute quit!');
//   process.exit(10002);
// }


//前置校验工作
// if (!verifyFileAndSign()) {
//     process.exit(10003);
// }

// 1、db添加对象、数据库添加数据              √√√√√√
addDbClass(projName,dbObj);
// process.exit(10200);

// 2、在controllers中创建projName.py，内容是  √√√√√√
createController(projName);
// process.exit(10201);

//3、app引入中使用                     √√√√√√
addAppBlueprint(projName);
// process.exit(10201);

// 4、前端src创建文件夹        √√√√√√
createDirIfNotExists(froSrc +'/' +projName);
// 4、创建vue文件和组件
createFroVue(projName, projPages, detailConfig);
// todo 正在进行vue文件生成的initProj()函数处理，初始化页面，和controllers的生成

//5 router中添加vue路径    √√√√√√
addRoutePath(projName,projPages);

//6 sideBar添加 将用不到了    √√√√√√
addSidBarPath(projName, projNameCh, projPages);

console.log('process end');





// TODO: 待完成
/**
 * 校验是否所有文件、内部标识符都齐全
 * @returns { boolean }  返回校验结果
 * */
function verifyFileAndSign() {
    // 检查文件和标识符是否都有

    //文件是否存在
    //标识符是否存在
    //相同代码是否存在
    //数据库是否存在
    //....


    return true;
}

/**
 *
 * 创建Controller后端文件
 * @param {string} projectName 项目名字
 *
 * */
function createController(projectName) {
    // 1、判断文件是否存在
    function hasFile(dir, filename) {
        const files = fs.readdirSync(dir);
        return files.includes(filename);
    }

    const dir = controllerSrc;
    const filename = `${projectName}.py`;

    if (hasFile(dir, filename)) {
        return console.log(`The directory ${dir} contains the file ${filename},文件${filename}已存在`);
    } else {
        const content = generateCode(projectName);

        createFileWithContent(dir, filename, content);
        console.log(`directory ${dir} , file ${filename}, create success`);
    }

    function createFileWithContent(dir, filename, content) {
        const filePath = path.join(dir, filename);
        fs.writeFileSync(filePath, content);
    }

    function generateCode(projectName) {

        const dbCaseStr = projectName.replace(/_([a-z])/g, (match, p1) => p1.toUpperCase()).replace(/^\w/, (match) => match.toUpperCase());
        let controlCode =
            `
from copy import deepcopy

import past
from flask import Blueprint, request, jsonify
from ${controllerSrcName}.common import *
from ${controllerSrcName}.db import *

${projectName}_api = Blueprint('${projectName}_api', __name__)
${projectName}_down_api = Blueprint('${projectName}_down_api', __name__)

@${projectName}_api.route('/${projectName}_action', methods=['GET', 'POST'])
def ${projectName}_action():
  params = json.loads(request.data)
  
 
  _action = params['action'] 
  methods={
    'add_data': addMethod,
    'delete_data': deleteMethod,
    'clone_data': cloneMethod,
    'update_method': updateMethod,
    'update_list_method': updateListMethod,
    'get_item_method': getItemMethod,
    'get_list_method': getListMethod,
  }
  # 获取并执行策略action，执行返回值code为0则表示正常
  action = methods.get(_action, nullMethod)
  result = action(params) 
  
  if result['code'] != 0:
    return {'status': result[code], 'info': result[info]}
  result_data = {'status': 200, 'data': result['data'], 'info': 'request success!'}
  return jsonify(result_data)

@${projectName}_down_api.route('/${projectName}_down_action/<int:is_push>', methods=['GET', 'POST'])
def ${projectName}_action(is_push):
  # params = json.loads(request.data)
  # is_push表示导出还是发布
  params = {
    "is_push": is_push
  }
  
  _action = 'push_issue'
  methods={
    'create_json': createJson,
    'push_issue': pushIssue,
  }
  # 获取并执行策略aciotn
  action = methods.get(_action, nullMethod)
  result = action(params)  
  
  # 直接返回push结果、不用特殊额外的处理
  return result


def nullMethod(param):
  return {'code': -1, 'data': '', 'info': '空方法'}


def addMethod(param):
  return {'code': -1, 'data': '', 'info': '方法未实现'}
  

def deleteMethod(param):
  dbObj = ${dbCaseStr}.query.filter_by(project=param['project']).first()
  db.session.delete(dbObj)
  db.session.commit()
  projectData = ${dbCaseStr}.query.filter_by(project=param['project']).first()
  if projectData is not None:
    return {'code': -2, 'data': '', 'info': 'projectData is not None,删除未成功'}
  else:
    return {'code': 0, 'data': '', 'info': '删除成功'}

def cloneMethod(param):
  data = ${dbCaseStr}.query.filter_by(project=param['project']).first()
  cloneObj = ${dbCaseStr}(${
                Object.entries(dbObj).map(([key, value]) => {
                    if (key == 'project') return '\n'
                    return `\t\t${key} = data.${key},\n`
                }).join('')}
    )
  db.session.add(cloneObj)
  db.session.commit()
  return {'code': 0, 'data': '', 'info': 'clone success'}


def updateMethod(param):
  project = param['project'] 
  item = param['data']${
              Object.entries(dbObj).map(([key, value]) => {
                  if (key == 'project') return '\n'
                  return `  if '${key}' in item:
    ${dbCaseStr}.query.filter_by(project=project).update({
      ${(() => {
                      let valueType = value.toLowerCase()
                      if (valueType.includes('int')) {
                          return `'${key}' : int(item['${key}'])`
                      }
                      if (valueType.includes('text')) {
                          return `'${key}' : json.dumps(item['${key}'])`
                      }
                  })()}
      })
    db.session.commit()\n`
              }).join('')}
  return {'code': 0, 'data': '', 'info': 'update success'}

def updateListMethod(param):
  pass

def getItemMethod(param):
  que = ${dbCaseStr}.query.filter_by(project=param['project']).first()
  if que is None:
    return -2  

  tmp = {
    ${
                Object.entries(dbObj).map(([key, value]) => {
                    return `${(() => {

                        let valueType = value.toLowerCase()
                        if (valueType.includes('int')) {
                            return `"${key}" : int(que.${key}),`
                        }
                        if (valueType.includes('text')) {
                            return `"${key}" : json.loads(que.${key}),`
                        }
                    })()}`
                }).join('\n\t')}
  }
  return {'code': 0, 'data': tmp, 'info': 'update success'}

def getListMethod(param):
  data = ${dbCaseStr}.query.order_by("project").all()
  result = [] 

  for que in data:
    tmp = {
      ${
                Object.entries(dbObj).map(([key, value]) => {
                    return `${(() => {
                        let preCode = ''
                        if(key!='project' && key!='remark') preCode = '#'
                        let valueType = value.toLowerCase()
                        if (valueType.includes('int')) {
                            return `${preCode}"${key}" : int(que.${key}),`
                        }
                        if (valueType.includes('text')) {
                            return `${preCode}"${key}" : json.loads(que.${key}),`
                        }
                    })()}`
                }).join('\n\t  ')}
    }
    result.append(tmp)
  return {'code': 0, 'data': result, 'info': 'update success'}


def createJson(param):
  pass

def pushIssue(param):
  is_push = param['is_push']
  list = ${dbCaseStr}.query.order_by("project").all()
  projs = {}
  for que in list:
    tmp = {
      ${
                Object.entries(dbObj).map(([key, value]) => {
                    return `${(() => {

                        let valueType = value.toLowerCase()
                        if (valueType.includes('int')) {
                            return `"${key}" : int(que.${key}),`
                        }
                        if (valueType.includes('text')) {
                            return `"${key}" : json.loads(que.${key}),`
                        }
                    })()}`
                }).join('\n\t  ')}
    }
    projs[que.project] = tmp
  return DownLoad('${projectName}', projs, is_push)



`
        return controlCode
    }

}

/**
 *
 * 创建数据库对象
 * @param {string} projectName 项目名字
 * @param {Object} dbObj 数据库配置
 *
 * */
function addDbClass(projectName, dbObj) {
    //1、创建数据库
    createTable(host, user, password, database, projName, dbObj, (res) => {
        console.log('create table err:', res)
    })


    //2、创建dbObj
    const _dbSrc = dbSrc
    const dbCaseStr = projName.replace(/_([a-z])/g, (match, p1) => p1.toUpperCase()).replace(/^\w/, (match) => match.toUpperCase());
    let dbStr = `
    
class ${dbCaseStr}(db.Model):
    __tablename__ = "${projName}"
    project = db.Column(db.Integer, primary_key=True, unique=True)  # id 整型，主键，自增，唯一 ${
        Object.entries(dbObj).map(([key, value]) => {
            if (key == 'project') return ''
            return `    ${key} = db.Column(db.${value})`
        }).join('\n')}
        
    def to_dict(self):
        pass
`
    appendCodeToFileEnd(_dbSrc, dbStr, dbCaseStr);
}

/**
 *
 * app中引入蓝图
 * @param {string} projectName 项目名字
 *
 */
function addAppBlueprint(projectName) {
    let haveImport = false
    let haveRegisterApi = false
    let haveRegisterDown = false
    const codeImport = `from ${controllerSrcName}.${projectName} import *`
    const codeRegisterApi = `app.register_blueprint(${projectName}_api, url_prefix='/')`
    const codeRegisterDown = `app.register_blueprint(${projectName}_down_api, url_prefix='/')`

    const filePath = appSrc;
    const lines = fs.readFileSync(filePath, 'utf-8').split('\n');

    //找到最后一行 import
    let lastImportIndex = -1;
    for (let i = lines.length - 1; i >= 0; i--) {
        //从最后一行找第一个import
        if (lines[i].startsWith('import') || lines[i].startsWith('from')) {
            if(lastImportIndex==-1) lastImportIndex = i;
        }
        if(lines[i].includes(codeImport)){
            haveImport = true
        }
    }

    const newLines = [
        codeImport
    ];
    if(haveImport){
        //    已经存在
        console.log('codeImport  已经存在');
    }else if (lastImportIndex !== -1) {
        // 在最后一行的前一行添加，指定没问题
        lines.splice(lastImportIndex + 0, 0, ...newLines);
    } else {
        console.log('app.py 文件为空，请构建好文件再使用');
    }

    //找到最后一行 register_blueprint,并添加
    let lastImportIndex2 = -1;
    for (let i = lines.length - 1; i >= 0; i--) {
        //从最后一行找第一个register_blueprint
        if (lines[i].startsWith('app.register_blueprint')) {
            if(lastImportIndex2==-1) lastImportIndex2 = i;
        }
        if(lines[i].includes(codeRegisterApi)) {
            haveRegisterApi = true
        }
        if(lines[i].includes(codeRegisterDown)) {
            haveRegisterDown = true
        }
    }

    //注册插入其中
    const newLines2 = [];
    if (!haveRegisterApi) newLines2.push(codeRegisterApi)
    if (!haveRegisterDown) newLines2.push(codeRegisterDown)
    if(haveRegisterApi == true && haveRegisterDown == true){
        //    已经存在
        console.log('codeRegisterApi & codeRegisterDown 已经存在');
    }else if (lastImportIndex2 !== -1) {
        // 在最后一行的前一行添加，指定没问题
        lines.splice(lastImportIndex2 + 0, 0, ...newLines2);
    } else {
        console.log('app.py 文件为空，请确认好文件再使用');
    }

    try {
        fs.writeFileSync(filePath, lines.join('\n'));
        console.log('add code to app.py success')
    } catch (err) {
        console.log('add code to app.py err:', err)
    }
}

/**
 *
 * 创建前端vue页面
 * @param {string} projectName 项目名字
 * @param {string[]} projPages 子页面名字
 * @param {string[]} detailConfig 子页面配置
 *
 */
function createFroVue(projectName, projPages, detailConfig) {
    //判断文件是否存在的函数
    function hasFile(dir, filename) {
        const files = fs.readdirSync(dir);
        return files.includes(filename);
    }

    //1、判断是否有index.vue文件，并决定是否创建
    const dir = path.resolve(froSrc, `${projectName}`);
    const filename = `index.vue`;
    if(hasFile(dir,filename)) {
        console.log(`src directory contains the file ${filename},文件${filename}已存在`);
    }else {
        let filePath = path.resolve(froSrc, `${projectName}`, 'index.vue')
        let code = generateFroIndexCodeByConfig(indexConfig)
        createFileWithCode(filePath, code);
    }

    //2、判断是否有detail.vue等文件，并决定是否创建
    projPages.forEach(pageName => {
        const dir = path.resolve(froSrc, `${projectName}`);
        const name = `${pageName}`;
        const filename = `${pageName}.vue`;
        if(hasFile(dir,filename)) {
            return console.log(`src directory contains the file ${filename},文件${filename}已存在`);
        }else {
            let filePath = path.resolve(froSrc, `${projectName}`, `${pageName}.vue`)
            if (detailConfig.hasOwnProperty(name)) {
                let code = generateDetailCode(projectName, detailConfig[name])
                createFileWithCode(filePath, code)
            }else{
                let code = generateNullCode({"name": name})
                createFileWithCode(filePath, code)
            }
        }
    })

    function generateNullCode(config) {
        let code =
            ` 
<template>
  <div>
    <h2>${config.name}页面，配置为空，请手动拷贝组件库代码，或修改配置后重来</h2>
  </div>
</template> 
`
        return code
    }


}

/**
 *
 * router中加入前端代码
 * @param {string} projectName 项目名字
 * @param {string[]} projPages 子页面名字
 *
 */
function addRoutePath(projectName, projPages) {
    const routerPath = routerIndexSrc
    let indexCode =
        `      {
        path: '/${projectName}',
        component: ()=>import('../${projectName}/index.vue')
      },`

    let codeArr = [
        indexCode
    ]

    projPages.forEach(item => {
        let code =
            `      {
         path: '/${projectName}/${item}',
         component: ()=>import('../${projectName}/${item}.vue')
      },`
        codeArr.push(code)
    })

    let filePath = routerPath
    let searchString = 'ly-router'
    let code = codeArr.join('\n')
    const fileContent = fs.readFileSync(filePath, 'utf8');
    if(fileContent.includes(`${projectName}`)){
        console.log(`Router中已经存在${projectName}(${projNameCh})项目的配置`)
    }else {
        const index = fileContent.indexOf(searchString);
        if (index !== -1) {
            const newContent = fileContent.slice(0, index + searchString.length) + '\n' + code + '\n' + fileContent.slice(index + searchString.length);
            fs.writeFileSync(filePath, newContent);
        }
    }

    // appendCodeToFile(routerPath, 'ly-router', codeArr.join('\n'))
}

/**
 *
 * router中加入前端代码
 * @param {string} projectName 项目名字
 * @param {string[]} projPages 子页面名字
 *
 */
function addSidBarPath(projectName, projNameCh, projPages) {
    let sideBarPath = sideBarSrc
    let indexCode =
        `        {
          icon: 'el-icon-setting',
          index: '/${projectName}',
          title: '${projNameCh}'
        },`

    let codeArr = [
        indexCode
    ]

    let filePath = sideBarPath
    let searchString = 'ly-sidebar'
    let code = codeArr.join('\n')
    const fileContent = fs.readFileSync(filePath, 'utf8');
    //判断是否已经存在
    if(fileContent.includes(`${projectName}`)){
        console.log(`sideBar中已经存在${projectName}(${projNameCh})项目的配置`)
    }else {
        const index = fileContent.indexOf(searchString);
        if (index !== -1) {
            const newContent = fileContent.slice(0, index + searchString.length) + '\n' + code + '\n' + fileContent.slice(index + searchString.length);
            fs.writeFileSync(filePath, newContent);
        }
    }

    // appendCodeToFile(sideBarPath, 'ly-sidebar', codeArr.join('\n'))

}


/**
 * 找到指定文件夹，若无则创建
 * @param {string|Buffer|URL} dirPath 指定创建目录的文件夹
 * @returns {null} 无返回
 */
function createDirIfNotExists(dirPath) {
    if (!fs.existsSync(dirPath)) {
        createDirIfNotExists(path.dirname(dirPath));
        fs.mkdirSync(dirPath);
        console.log()
    }
}


/**
 * 在指定的目录下，创建指定文件，并向文件中写入动态生成的代码
 * @param {string} filePath 路径
 * @param {string|Buffer} code 文件代码
 * */
function createFileWithCode(filePath, code) {
    createDirIfNotExists(path.dirname(filePath));
    fs.writeFileSync(filePath, code);
}


/**
 * 在指定的文件，指定代码后添加代码
 * @param {string} filePath 路径
 * @param {string} searchString 指定代码
 * @param {string|Buffer} code 文件代码
 * */
function appendCodeToFile(filePath, searchString, code) {
    const fileContent = fs.readFileSync(filePath, 'utf8');
    const index = fileContent.indexOf(searchString);
    if (index !== -1) {
        const newContent = fileContent.slice(0, index + searchString.length) + '\n' + code + '\n' + fileContent.slice(index + searchString.length);
        fs.writeFileSync(filePath, newContent);
    }
}


/**
 * 在指定文件的最后一行添加代码
 * @param {string} filePath - 文件路径（相对路径或绝对路径）
 * @param {string} code - 要添加的代码
 * @param {string} dbCaseStr - 数据库大写名称
 */
function appendCodeToFileEnd(filePath, code, dbCaseStr) {
    // 读取文件内容
    const content = fs.readFileSync(filePath, 'utf8');

    if(content.includes(dbCaseStr)){
        console.log('db.py中 已经存在映射对象')
        return
    }

    // 将要添加的代码添加到文件内容的末尾
    const newContent = `${content}${code}`;

    // 将新的内容写入文件
    fs.writeFileSync(filePath, newContent, 'utf8');
}


/**
 * 在指定数据库中创建一个表
 * @param {string} host - 数据库主机名
 * @param {string} user - 数据库用户名
 * @param {string} password - 数据库密码
 * @param {string} database - 数据库名
 * @param {string} tableName - 要创建的表名
 * @param {object} columns - 表的列定义，格式为 { columnName: columnType }
 * @param {function} callback - 回调函数，接受一个错误对象作为参数
 */
function createTable(host, user, password, database, tableName, columns, callback) {
    // 创建数据库连接
    const connection = mysql.createConnection({
        host,
        user,
        password,
        database,
    });

    // console.log('11111111111111')

    // 连接数据库
    let temp = connection.connect((err) => {
        // console.log('11111111111111')
        if (err) {
            callback(err);
            return;
        }
        console.log('数据库连接成功');

        connection.query(`SHOW TABLES  LIKE '${projName}'`, function (error, results, fields) {
            if (error) throw error;
            if (results.length > 0) {
                console.log(`${tableName} Database exists,数据库已经存在`);
                // 关闭数据库连接
                connection.end();
            } else {
                console.log('Database does not exist');
                // 执行 SQL 语句创建表
                const sql = `CREATE TABLE ${tableName} (${Object.entries(columns)
                    .map(([name, type]) => `${name} ${type}`)
                    .join(', ')})`;
                connection.query(sql, (err) => {
                    if (err) {
                        callback(err);
                    } else {
                        callback(null);
                    }
                    // 关闭数据库连接
                    connection.end();
                });
            }
        });

    });


    console.log('222222222222222222222222')

    // 监听数据库连接错误事件
    connection.on('error', (err) => {
        console.error('数据库连接错误', err);
        callback(err);
    });

}


//一下是生成前端index代码的函数
function generateFroIndexCodeByConfig(indexConfig) {
    const barFunc = indexConfig.barFunc
    const tabBarFunc  = indexConfig.indexTab.barFunc
    const formInfo  = indexConfig.indexTab.form
   let code =
`
<template>
  <div class="project-main-box">
    <div ref="headBar" style="overflow: visible" :style="{ height: divHeight  + 'px', transition: 'height 0.5s' }">
      <div class="head-bar">
        <span class="head-title">${projNameCh}</span>
        <span class="head-button-box">
          <el-button type="primary"  size="medium" round class="head-button" @click="pushJson(0)">导出Json文件</el-button>
          <el-button type="success"  size="medium" round class="head-button" @click="pushJson(1)">发布到平台</el-button>
          <el-upload style="float: right;" class="upload-demo" ref="upload" accept=".xlsx" :action="UploadUrl()" :on-preview="handlePreview"
                     :on-remove="handleRemove" :file-list="fileList" :auto-upload="false" :on-success="handleUploadSuccess">
             <el-button slot="trigger" size="small" round type="primary" class="head-button" >选择文案EXCEL</el-button>
             <el-button size="small" type="success" round @click="submitUpload" class="head-button">上传</el-button>
          </el-upload>
        </span>
      </div>
    </div>
    <!--  main身体主要框  -->
    <div class="main-box-body" v-if="loaded">
      <el-tabs v-model="activeTab" @tab-click="changeTabs">

        <!--  form模块   -->
        <el-tab-pane label="活动方案"  name="first" class="tab-box">
          <!-- 内容盒子，建议放组件  -->
          <div class="tab-item-box" ref="tabItemBox" v-if="activeTab=='first'">
              <div class="tab-item-head">
                <span class="tab-item-left">
                  <!--  <remark-template action="${projName}"></remark-template>--> 
                  <el-input v-model="searchValue" disabled size="medium"></el-input>
                  <el-button icon="el-icon-search" style="margin-left: 10px" size="medium" disabled circle @click="clickFunc('搜索')"></el-button>
                  <el-button type="success" icon="el-icon-check" style="margin-left: 10px" disabled size="medium" circle @click="clickFunc('搜索')"></el-button>
                </span>
                <span class="tab-item-right">
                  <el-button  style="color: #1989fa" icon="el-icon-plus" size="medium" round class="item-head-button" @click="clickFunc">新建</el-button>
                  <el-button style="color:rgb(10,194,58);" icon="el-icon-check" size="medium" round class="item-head-button" @click="clickFunc">保存</el-button>
                </span>
              </div>
            <!--   主要内容模块    -->
            <div class="tab-item-body" ref="tabItemBody">
              <el-table  ref="singleTable" border :data="this.tableList"
                  highlight-current-row header-align="center" style="width: 100%" row-height="30"
                  @current-change="clickChangeTable">
<!--                <el-table-column-->
<!--                    width="50">-->
<!--                </el-table-column>-->
                <el-table-column
                    property="project"
                    label="方案id"
                    align="center"
                    width="100">
                  <template  slot-scope="scope">
                    <span>{{scope.row.id!=-1?scope.row.project:'未更新'}}</span>
                  </template>
                </el-table-column>
                <el-table-column height="60px"
                    align="center"
                    property="remark"
                    label="备注remark"
                    min-width="700">
                  <template  slot-scope="scope">
                    <el-input size="medium" v-model="scope.row.remark.remark1" @input="inputRemark(scope.$index)" @blur="clickSaveRemark(scope.$index, scope.row)" style="width:400px;" ></el-input>
                  </template>                     
                </el-table-column>
                
                <el-table-column label="操作"  align="center" width="250px" class="action-column">
                  <template slot-scope="scope">
                    <el-button
                        size="small" plain type="primary" icon="el-icon-document-copy" class="ly-mini-button"
                        @click="clickCloneTable(scope.$index, scope.row)">克隆</el-button>
                    <el-button
                        size="small" plain type="primary" icon="el-icon-info"  class="ly-mini-button"
                        @click="clickInfoTable(scope.$index, scope.row)">详情</el-button>
                    <el-button
                        size="small" type="danger" plain icon="el-icon-delete"  class="ly-mini-button"
                        @click="deleteCloneTable(scope.$index, scope.row)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <span class="scroll-top"  @click="scrollToTop">
                <el-popover
                    placement="top-start"
                    width="200"
                    trigger="hover"
                    content="点击返回最上，向上滚动展示导航条">
                  <span slot="reference" >
                    <i class="el-icon-upload2"></i>
                  </span>
              </el-popover>
              </span>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script> 
export default { 
  name: "index",
  data(){
    return {
      rows: {},
      loaded: true, //主页显示
      activeTab: 'first', //加载的tab
      divHeight: 60, //头部导航栏的动态增减
      searchValue: '请输入备注', //搜索值
      fileList: [], //文件上传
      tableList: [{id:0,remark:'remark0',goods:'[1,2,3]'},{id:1,remark:'remark1',goods:'[1,2,3]'}],
      formData: {name: '', region: '', date1: '', date2: '', delivery: false, type: [], resource: '', desc: ''},
      //校验规则
      rules: {
        name: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        region: [
          { required: true, message: '请选择活动区域', trigger: 'change' }
        ],
        date1: [
          { type: 'date', required: true, message: '请选择日期', trigger: 'change' }
        ],
        date2: [
          { type: 'date', required: true, message: '请选择时间', trigger: 'change' }
        ],
        type: [
          { type: 'array', required: true, message: '请至少选择一个活动性质', trigger: 'change' }
        ],
        resource: [
          { required: true, message: '请选择活动资源', trigger: 'change' }
        ],
        desc: [
          { required: true, message: '请填写活动形式', trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    const myDiv = this.$refs.tabItemBox;
    // myDiv.addEventListener('wheel', this.handleWheel);
  },
  beforeDestroy() {
    const myDiv = this.$refs.tabItemBox;
    if(myDiv) myDiv.removeEventListener('wheel', this.handleWheel);
  },
  async created() {
    await this.initAll();
  },
  methods:{
    //数据初始化
    async initAll(){ 
      this.loaded = false
      await this.initProjs()
      this.loaded = true      
      this.reloadListen()
    },
    async initProjs(){
      let param = {
        "action": "get_list_method"
      }
      let { data:res } = await this.axios.post(this.$settings.HOST + '/${projName}_action',param)
      if(res.status == 200){
        this.$message.success('Load Data Success')
        this.tableList = res.data
      }else {
        this.$message.error(\`\${res.info}\`)
      }
    },

    //重新启动监听
    reloadListen(){
      this.$nextTick(() => {
        // 在DOM更新后执行回调函数
        // this.divHeight = 200;
        const myDiv = this.$refs.tabItemBox;
        myDiv.removeEventListener('wheel', this.handleWheel);
        myDiv.addEventListener('wheel', this.handleWheel);
      });
    },
    //监听滚动事件
    handleWheel(event) {
      console.log('handleScroll')
      const myDiv = this.$refs.headBar;
      const tabItemBox = this.$refs.tabItemBox;
      if (event.deltaY > 0) {
        this.divHeight = 0;
        myDiv.style.overflow = 'hidden';
        if(tabItemBox) tabItemBox.style.height = 'calc(100vh - 165px)';

      } else {
        this.divHeight = 60;
        myDiv.style.overflow = 'visible';
        tabItemBox.style.height = 'calc(100vh - 225px)';
      }
    },
    //默认点击事件
    clickFunc(){
      console.log('clickFunc')
    },
    //tabs切换事件
    changeTabs(tab){
      console.log('changeTabs,选中的实例',tab);
      let event = {}
      event.deltaY = -20
      this.handleWheel(event);//设置head-bar默认高度
      this.reloadListen(); //重新启动监听
    },
    clickCloneTable(index,row){
      this.$confirm(\`克隆id=\${row.project},remark= \${row.remark.remark1}, 是否继续?\`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let param = {
          action : 'clone_data',
          project: row.project
        }
        let { data:res } = await this.axios.post(this.$settings.HOST + '/${projName}_action',param)
        if(res.status == 200){
          this.$message.success('clone success')
          this.initAll();
        }else {
          this.$message.error(\`\${res.info}\`)
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },
    //具体模块操作
    //1、form模块
    submitForm(){

    },
    resetForm(){

    },
    // 2、table模块
    clickChangeTable(){

    },
    clickInfoTable(index,row){
      this.$router.push({
        path: "/${projName}/inline",
        query: {
          project: row.project
        },
      });
    },
    deleteCloneTable(index,row){
      this.$confirm(\`删除id=\${row.project},remark= \${row.remark.remark1}, 是否继续?\`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let param = {
          action : 'delete_data',
          project: row.project
        }
        let { data:res } = await this.axios.post(this.$settings.HOST + '/${projName}_action',param)
        if(res.status == 200){
          this.$message.success('delete success')
          this.initAll();
        }else {
          this.$message.error(\`\${res.info}\`)
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },
    inputRemark(index){
      this.rows[index] = true
    },
    async clickSaveRemark(index,row){
      if(this.rows[index] != true) return
      let param = {
        action : 'update_method',
        data: {
          "remark":row.remark
        },
        project: row.project
      }
      let { data:res } = await this.axios.post(this.$settings.HOST + '/${projName}_action',param)
      if(res.status == 200){
        this.$message.success(\`update project :\${row.project}(\${row.remark.remark1}) remark success\`)
        this.rows[index] = false
        // this.initAll();
      }else {
        this.$message.error(\`\${res.info}\`)
      } 
    },
    //模块通用操作
    scrollToTop() {
      this.$refs.tabItemBox.scrollIntoView({ behavior: 'smooth', block: 'start' });
      // this.$refs.tabItemBox.scrollIntoView({ behavior: 'smooth', block: 'start' });
    },

    async pushJson(is_push){
      // let { data:res }  = await this.axios.post(this.$settings.HOST + '/rotary_reward_proj_down_action',)

      if (is_push == 0) {
        window.location.href = this.$settings.HOST + "/${projName}_down_action/" + is_push
      } else {
        this.axios.get(this.$settings.HOST + "/${projName}_down_action/" + is_push)
            .then(response => {
              this.$message({
                message: '上传成功',
                type: 'success',
                showClose: true,
                offset: 300
              });
            }).catch(function(error) { // 请求失败处理
          console.log(error);
        });
      }
    },
    
     //文件上传
    UploadUrl() {
      return this.$settings.HOST + "/upload/${projName}"
    },
    submitUpload() {
      this.$refs.upload.submit()
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    async handleUploadSuccess() {
      this.$message({
        type: 'success',
        message: '上传成功'
      });
      await this.initProjs()
    },
  }
}
</script>


<style scoped>
/*非侵入修改主题*/
html{
  background-color: #F5F7FA;
  height: 100vh;
}
body{
  margin: 0px!important;
}
/*tab样式*/
>>>  .el-tabs__nav-wrap::after{
  height: 0px!important;
  /*margin-left: 10px!important;*/
}
.el-main::-webkit-scrollbar {
  display: none;
}
.el-aside{
  width: 230px!important;
}
.el-main {
  padding: 10px 0 0 0!important;
}
.el-container >>  .el-main{
  padding: 10px 0 0 0;
  background-color: #F5F7FA;
  height: calc(99vh - 65px) !important;
  width: calc(99% - 10px);
  overflow-x: hidden;
  /*overflow-y: hidden*/
}
.el-header {
  background-color: rgb(186 230 253);
  /*background-color: #B3C0D1;*/
  color: #333;
  line-height: 80px;
}

/*主框架内容*/
.project-main-box{
  position: fixed;
  top: 60px;
  right: 0px;
  background-color: #F5F7FA;
  width: calc(97% - 170px);
  height: calc(100% - 60px);
  /*position: relative;*/
  padding: 20px;
  padding-top: 5px;
  /*overflow: auto;*/
}
/*头部bar*/
.head-bar{
  position: sticky;
  top: 10px;
  display: flex;
  width: calc(100% - 30px);
  padding: 5px 10px 5px 20px;
  border-radius: 10px;
  background-color: white;
  justify-content: space-between;
  align-items: center;
  z-index: 1000;
  border: 1px solid #F5F7FA;
  box-shadow:  2px 2px 5px 5px  rgba(219, 219, 219, 0.5);
}
.head-title{
  font-size: larger;
  font-weight: bolder;
  font-family: '微软雅黑';
}
.head-button-box{
  display: flex;
  justify-content: right;
}
.head-button{
  padding: 10px 30px 10px 30px!important;
  min-width: 80px;
  margin-right: 10px
}

/*身体部分*/
.main-box-body{
  width: 100%;
  /*margin-top: 50px;*/
  background-color: #F5F7FA;
  margin-top: 10px;
  /*padding: 10px 10px 10px 20px;*/
  border-radius: 10px;
  max-height: calc(100vh - 205px);
}
/*tab样式*/
.el-tabs__content{
  overflow: visible!important;
}
.el-tabs__nav{
  padding-left: 10px!important;
}
.el-tabs__active-bar{
  padding-left: 20px!important;
}
.el-tabs__nav-wrap::after{
  height: 0px!important;
  /*margin-left: 10px!important;*/
}
.el-tabs__content{
  top : -8px;
}
.el-tabs{
  position: relative;
}
.tab-box{
  background-color: #ffffff;
  padding: 10px;
  border-radius: 10px;
  position: relative;
  /*max-height: calc(100vh - 200px);*/
  box-shadow: 2px 2px 5px 5px rgba(219, 219, 219, 0.5);
}
.item-head-button{
  padding: 8px 20px 8px 20px!important;
  min-width: 80px;
  margin-right: 9px
}


/*每一个tab项的*/
.tab-item-box{
  overflow: auto;
  position: relative;
  height: calc(100vh - 225px);
}
.tab-item-head{
  position: sticky;
  top: 0;
  min-height: 30px;
  display: flex;
  justify-content: space-between;
  margin: 0 0 10px 0;
  /*background-color: rgba(0, 255, 149, 0.1);*/
  box-shadow: 0px 10px 10px white;
  z-index: 1000;
  background-color: rgba(255, 255, 255, 0.8);
}
.tab-item-left{
  display: flex;
}
.tab-item-right{

}
.tab-item-body{
  margin-top: 20px;
  position: relative;
  /*background-color: #409EFF;*/
  /*height: 150vh;*/
}

/*模块通用操作*/
.scroll-top{
  padding: 4px;
  height: 20px;
  width: 20px;
  line-height: 20px;
  border-radius: 5px;
  background-color: #f2f5f6;
  box-shadow: 0 0 3px 2px rgba(25,137,250, .1);
  text-align: center;
  color: #1989fa;
  position: sticky;
  float: right;
  right: 4px;
  bottom: 4px;
  border: 1px solid #cae4fd;
  opacity: 0.9;
}
.scroll-top:hover{
  cursor: pointer;
}

/*其他系统ui-css*/
/*按钮设置*/
.ly-mini-button{
  padding: 8px!important;
}
</style>

`
    return code
}

function generateIndexFromItem(config) {

}

function generateDetailCode(projName, config) {
    //判断文件是否存在的函数
    function hasFile(dir, filename) {
        const files = fs.readdirSync(dir);
        return files.includes(filename);
    }

    //生成子组件
    // for (let detailConfigElement of detailConfig[name]) {
    //     const compName = detailConfigElement["name"]
    //     const dir = path.resolve(froSrc, `${projName}`, "inline");
    //     const filename = `${compName}.vue`;
    //     if(hasFile(dir,filename)) {
    //         return console.log(`directory ${dir},文件${filename}已存在`);
    //     }else {
    //         let filePath = path.resolve(froSrc,  `${projName}`, "inline" , `${compName}.vue`)
    //         let codeComp = generateDetailCompCode(detailConfigElement)
    //         createFileWithCode(filePath, codeComp)
    //     }
    // }

    //生成html tab
    function genHtmlTab(){
        let tabCode = ''
        config.forEach(elementConfig=>{
            let code =
            `
            <el-tab-pane label="${elementConfig.label}"  name="${elementConfig.comp_name}" class="tab-box">
                <!-- 内容盒子，建议放组件  -->
                <div class="tab-item-tab-box" v-if="activeTab==='${elementConfig.comp_name}'" ref="tabItemBox">
                    <${elementConfig.comp_name}></${elementConfig.comp_name}>
                </div>
            </el-tab-pane>
          
            `
            tabCode += code
        })
        return tabCode
    }

    //生成js import
    function genJsCompImport() {
        // 转为驼峰模式
        function transStr(str) {
            console.log('str',str)
            return  camelCaseStr = str.split("-").map((word, index) => {
                if (index === 0) {
                    return word;
                } else {
                    return word.charAt(0).toUpperCase() + word.slice(1);
                }
            }).join("");
        }

        let importCode = '\n'
        config.forEach(elementConfig=>{
            let compName  = transStr(elementConfig.comp_name)
            let code = `import ${compName} from "./inline/${elementConfig.comp_name}.vue";\n`
            importCode += code
        })
        return importCode
    }

    // 转为驼峰模式
    function transStr(str) {
        return  camelCaseStr = str.split("-").map((word, index) => {
            if (index === 0) {
                return word;
            } else {
                return word.charAt(0).toUpperCase() + word.slice(1);
            }
        }).join("");
    }



    let code =
`
<template>
  <div class="project-main-box">
    <div ref="headBar" style="overflow: visible" :style="{ height: divHeight  + 'px', transition: 'height 0.5s' }">
      <div class="head-bar">
        <span class="head-title">
          <span @click="clickBacktoMain" class="click-back">返回${projNameCh}主页/</span>
          <span style="font-weight: normal">id={{this.$route.query.project}}</span>
        </span>
        <span class="head-button-box">
          <el-upload style="float: right;margin-right: 20px" class="upload-demo" ref="upload" accept=".xlsx" :action="UploadUrl()" :on-preview="handlePreview"
                     :on-remove="handleRemove" :file-list="fileList" :auto-upload="false" :on-success="handleUploadSuccess">
             <el-button slot="trigger" class="head-button" round type="primary">选择文案EXCEL</el-button>
             <el-button class="head-button" type="success" round @click="submitUpload">上传</el-button>
          </el-upload>
          <el-button type="primary"  size="medium" round class="head-button" @click="pushJson(0)">导出Json文件</el-button>
          <el-button type="primary"  size="medium" round class="head-button" @click="pushJson(1)">发布</el-button>
        </span>
      </div>
    </div>
    <!--  main身体主要框  -->
    <div class="main-box-body" v-if="loaded">
      <el-tabs v-model="activeTab" @tab-click="changeTabs">
        ${genHtmlTab()} 
      </el-tabs>
    </div>
  </div>
</template>

<script> 
import bus from "../common/bus";
${genJsCompImport()}
export default {
  name: "index",
  components: {${Object.entries(config).map(([key,value])=>{
      return transStr(value.comp_name)}).join(",")}},
  data(){
    return {
      loaded: false, //主页显示
      activeTab: '${config[0].comp_name}', //加载的tab
      divHeight: 60, //头部导航栏的动态增减
      fileList: [], //文件列表

      searchValue: 'searchValue/remark', //搜索值
      changeRow: {}, //改变时显现保存
      tableList: [{id:0,remark:'remark0',goods:'[1,2,3]'},{id:1,remark:'remark1',goods:'[1,2,3]'}],
      formData: {},
      //校验规则
      rules: {},

      itemData: {
        tableList: [
          {proj:0,remark:'remark0',goods:[{a:[0,1,1]},{a:[0,1,1]}]},
          {proj:1,remark:'remark1',goods:[{a:[0,1,1]},{a:[0,1,2]},{a:[0,1,3]}]},
          {proj:2,remark:'remark2',goods:[{a:[0,1,11]},{a:[0,1,22]}]}],
      },
    }
  },
  mounted() {
    // const myDiv = this.$refs.tabItemBox;
    // myDiv.addEventListener('wheel', this.handleWheel);
  },
  beforeDestroy() {
    //添加页面滚动监听
    // const myDiv = this.$refs.tabItemBox;
    // myDiv.removeEventListener('wheel', this.handleWheel);


    //取消监听tab切换改变
    //取消监听重绘页面
    //取消监听init页面
    bus.$off('change-tab', this.busChangeTab);
    bus.$off('reload-page', this.busReloadPage);
    bus.$off('init-page', this.busInitPage);
  },
  async created() {
    //监听tab切换改变
    bus.$on('change-tab', this.busChangeTab)
    //监听重绘页面
    bus.$on('reload-page', this.busReloadPage)
    //监听init页面
    bus.$on('init-page', this.busInitPage)
    //监听页面滚动
    bus.$on('handle-wheel', this.busHandleWheel)

    await this.initAll()
  },
  methods:{
    //定义事件监听的事件
    //切换tab 、重绘页面 、重载页面
    busChangeTab(params){
      console.log('change-tab',params)
      if (params.tabIndex !== undefined) this.activeTab = params.tabIndex
    },
    busReloadPage(params){
      console.log('reload-page',params)
      if (params.tabIndex !== undefined) this.activeTab = params.tabIndex
    },
    busInitPage(params){
      console.log('init-page',params)
      if (params.tabIndex !== undefined) this.activeTab = params.tabIndex
    },
    busHandleWheel(params){
      console.log('handle-wheel',params)
      let event = params.event

      const myDiv = this.$refs.headBar;
      if (event.deltaY > 0) {
        this.divHeight = 0;
        myDiv.style.overflow = 'hidden';

      } else {
        this.divHeight = 60;
        myDiv.style.overflow = 'visible';
      }

      console.log('handleScroll----------------')
      const tabItemBox = this.$refs.tabItemBox ;
      if (event.deltaY > 0) {
        if(tabItemBox) tabItemBox.style.height = 'calc(100vh - 175px)';

      } else {
        tabItemBox.style.height = 'calc(100vh - 235px)';
      }
    },


    //返回主页
    clickBacktoMain(){
      this.$router.push({
        path: "/${projName}"
      });
    },
    //重新启动监听
    reloadListen(){
      this.$nextTick(() => {
        // 在DOM更新后执行回调函数
        // this.divHeight = 200;
        const myDiv = this.$refs.tabItemBox;
        myDiv.removeEventListener('wheel', this.handleWheel);
        myDiv.addEventListener('wheel', this.handleWheel);
      });
    },
    //监听滚动事件
    handleWheel(event) {
      console.log('handleScroll')
      const myDiv = this.$refs.headBar;
      const tabItemBox = this.$refs.tabItemBox;
      if (event.deltaY > 0) {
        this.divHeight = 0;
        myDiv.style.overflow = 'hidden';
        if(tabItemBox) tabItemBox.style.height = 'calc(100vh - 175px)';

      } else {
        this.divHeight = 60;
        myDiv.style.overflow = 'visible';
        tabItemBox.style.height = 'calc(100vh - 235px)';
      }
    },
    //tabs切换事件
    changeTabs(tab){
      console.log('changeTabs,选中的实例',tab);
      let event = {}
      event.deltaY = -20
      this.$nextTick(() => {
        this.handleWheel(event);//设置head-bar恢复默认高度
      })
      this.reloadListen();
    },
    //滚动置顶通用操作
    scrollToTop() {
      this.$refs.tabItemBox.scrollIntoView({ behavior: 'smooth', block: 'start' });
      // this.$refs.tabItemBox.scrollIntoView({ behavior: 'smooth', block: 'start' });
    },
    //上传文件
    UploadUrl() {
      return this.$settings.HOST + "/upload/${projName}_proj"
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
      this.$message.success('re ok')
    },
    async handleUploadSuccess() {
      this.$message({
        type: 'success',
        message: '上传成功'
      });
      // await this.initDta()
    },
    submitUpload() {
      return this.$message.error("请完成后端代码并完善前端逻辑")
      this.$refs.upload.submit()
      this.$message.success('ok')
    },
    handlePreview(file) {
      console.log(file);
    },
    //发布和导出 TODO:
    pushJson(is_push){
      if (is_push == 0) {
        window.location.href = this.$settings.HOST + "/${projName}_action/" + is_push
      } else {
        this.axios.get(this.$settings.HOST + "/${projName}_down_action/" + is_push)
            .then(response => {
              this.$message({
                message: '上传成功',
                type: 'success',
                showClose: true,
                offset: 300
              });
            }).catch(function(error) { // 请求失败处理
          console.log(error);
        });
      }
    },

    //初始化
    async initAll(){
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      this.loaded = false

      //获取列表 TODO:
      // await this.getReward()
      // await this.getBonusList()
      //获取数据 TODO:
      // await this.getProjectList()
      await this.getProject()

      this.$nextTick(() => {
        this.loaded = true
      })
      // this.loaded = true
      loading.close();
      this.reloadListen();
    },
    //获取单项数据
    async getProject(){
      let param = {
        action:'get_item_method',
        "project":this.$route.query.project
      }
      let { data:res } = await this.axios.post(this.$settings.HOST + '/${projName}_action',param)
      if(res.status == 200){
        this.$message.success('load data success')
        this.itemData = res.data
        // this.$store.state.itemData = this.itemData
        await this.$store.commit('update',['itemData',res.data ])
        this.$store.state.itemData = this.itemData
        this.loaded = true
        this.$nextTick(() => {
          //table表单在第一页时需要顾及排序
          // this.setSort()
        })
      }else {
        this.$message.error(\`数据加载失败：\${res.info}\`)
      }
    },
    //获取数据列表
    async getProjectList(){
      let param = {
        "action": "get_list_method"
      }
      let { data:res } = await this.axios.post(this.$settings.HOST + '/${projName}_action',param)
      if(res.status == 200){
        this.$message.success('Load Data Success')
        this.tableList = res.data
      }else {
        this.$message.error(\`\${res.info}\`)
      }
    },

    //获取奖励list
    async getReward(){
      let query = {}
      query.action = "get_proj_list"
      const res = await this.axios.get(this.$settings.HOST + '/reward_type_list/')
      if (res.data.data === undefined){
        this.$store.commit('update',['rewardList',res.data])
      }else {
        this.$store.commit('update',['rewardList',res.data.data])
      }
      this.reward_type_list = res.data.data
      console.log('rewardList:',res.data.data)
    },
    async getBonusList(){
      let query = {}
      const res = await this.axios.get(this.$settings.HOST + '/bonusList/')
      this.$store.commit('update',['bonusList',res.data])
      this.bonusList = res.data
      console.log('bonusList:',res.data)
    },
  }
}
</script>

<style scoped>
/*非侵入修改主题*/
html{
  background-color: #F5F7FA;
  height: 100vh;
}
body{
  margin: 0px!important;
}
/*tab样式*/
>>>  .el-tabs__nav-wrap::after{
  height: 0px!important;
  /*margin-left: 10px!important;*/
}
.el-main::-webkit-scrollbar {
  display: none;
}
.el-aside{
  width: 230px!important;
}
.el-main {
  padding: 10px 0 0 0!important;
}
.el-container >>  .el-main{
  padding: 10px 0 0 0;
  background-color: #F5F7FA;
  height: calc(99vh - 65px) !important;
  width: calc(99% - 10px);
  overflow-x: hidden;
  /*overflow-y: hidden*/
}
.el-header {
  background-color: rgb(186 230 253);
  /*background-color: #B3C0D1;*/
  color: #333;
  line-height: 80px;
}

/*主框架内容*/
.project-main-box{
  position: fixed;
  top: 60px;
  right: 0px;
  background-color: #F5F7FA;
  width: calc(97% - 170px);
  height: calc(100% - 60px);
  /*position: relative;*/
  padding: 20px;
  padding-top: 5px;
  /*overflow: auto;*/
}
/*头部bar*/
.head-bar{
  position: sticky;
  top: 10px;
  display: flex;
  width: calc(100% - 30px);
  padding: 5px 10px 5px 20px;
  border-radius: 10px;
  background-color: white;
  justify-content: space-between;
  align-items: center;
  z-index: 1000;
  border: 1px solid #F5F7FA;
  box-shadow:  2px 2px 5px 5px  rgba(219, 219, 219, 0.5);
}
.head-title{
  font-size: larger;
  font-weight: bolder;
  font-family: '微软雅黑';
}
.head-button-box{
  display: flex;
  justify-content: right;
}
.head-button{
  padding: 10px 30px 10px 30px!important;
  min-width: 80px;
  margin-right: 10px
}

.click-back:hover{
  cursor: pointer;
}

/*身体部分*/
.main-box-body{
  width: 100%;
  /*margin-top: 50px;*/
  background-color: #F5F7FA;
  margin-top: 10px;
  /*padding: 10px 10px 10px 20px;*/
  border-radius: 10px;
  max-height: calc(100vh - 205px);
}
/*tab样式*/
.el-tabs__content{
  overflow: visible!important;
}
.el-tabs__nav{
  padding-left: 10px!important;
}
.el-tabs__active-bar{
  padding-left: 20px!important;
}
.el-tabs__nav-wrap::after{
  height: 0px!important;
  /*margin-left: 10px!important;*/
}
.el-tabs__content{
  top : -8px;
}
.el-tabs{
  position: relative;
}
.tab-box{
  background-color: #ffffff;
  padding: 10px;
  border-radius: 10px;
  position: relative;
  /*max-height: calc(100vh - 200px);*/
  box-shadow: 2px 2px 5px 5px rgba(219, 219, 219, 0.5);
}
.item-head-button{
  padding: 8px 20px 8px 20px!important;
  min-width: 80px;
  margin-right: 9px
}


/*每一个tab项的*/
.tab-item-box{
  overflow: auto;
  position: relative;
  height: calc(100vh - 225px);
}
.tab-item-head{
  position: sticky;
  top: 0;
  min-height: 30px;
  display: flex;
  justify-content: space-between;
  margin: 0 0 10px 0;
  /*background-color: rgba(0, 255, 149, 0.1);*/
  box-shadow: 0px 10px 10px white;
  z-index: 1000;
  background-color: rgba(255, 255, 255, 0.8);
}
.tab-item-left{
  display: flex;
}
.tab-item-right{

}
.tab-item-body{
  margin-top: 20px;
  position: relative;
  /*background-color: #409EFF;*/
  /*height: 150vh;*/
}

/*模块通用操作*/
.scroll-top{
  padding: 4px;
  height: 20px;
  width: 20px;
  line-height: 20px;
  border-radius: 5px;
  background-color: #f2f5f6;
  box-shadow: 0 0 3px 2px rgba(25,137,250, .1);
  text-align: center;
  color: #1989fa;
  position: sticky;
  float: right;
  right: 4px;
  bottom: 4px;
  border: 1px solid #cae4fd;
  opacity: 0.9;
}
.scroll-top:hover{
  cursor: pointer;
}

/*其他系统ui-css*/
/*按钮设置*/
.ly-mini-button{
  padding: 8px!important;
}
</style>
`

    return code
}


function generateDetailCompCode(elementConfig) {
    let code =
`
<template>
  <div  >
    <div class="tab-item-box" ref="tabItemBox">
      <div v-if="loaded" class="tab-item-head" >
        <span class="tab-item-left">
          <el-input v-model="remark.remark0" style="min-width: 300px" class="remark-search-input"   type="textarea" autosize  ></el-input>
          <el-button icon="el-icon-search" class="head-left-button" size="medium"  @click="headSearchFunc('搜索')">搜索</el-button>
          <el-button type="success" icon="el-icon-check" class="head-left-button"  plain size="medium"   @click="saveRemark()">备注</el-button>
        </span>
        <span class="tab-item-right">
          <el-button style="color: #ffffff" icon="el-icon-plus" size="medium" type="primary" round class="item-head-button" @click="headAddFunc">新建</el-button>
          <el-button style="color: #ffffff;" icon="el-icon-check" size="medium" type="success" round class="item-head-button" @click="headSaveFunc">保存</el-button>
        </span>
      </div>
      <!--   主要内容模块    -->
      <div class="tab-item-body" ref="tabItemBox">
        <div  v-if="loaded" class="main-body-content"  style="">
          <h2>标题</h2>
            {{formData}}
          <el-form :model="formData" :rules="rules" ref="formData"  label-width="100px" class="demo-ruleForm">
            <el-form-item label="活动名称" prop="name">
              <el-input v-model="formData.name"></el-input>
            </el-form-item>
            <el-form-item label="number" prop="name">
              <el-input v-model.number="formData.number"/>
            </el-form-item>
            <el-form-item label="活动区域" prop="region">
              <el-select v-model="formData.region" placeholder="请选择活动区域">
                <el-option label="区域一" value="shanghai"></el-option>
                <el-option label="区域二" value="beijing"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="即时配送" prop="delivery">
              <el-switch v-model="formData.delivery" active-text="a" active-value="" inactive-text="ina" inactive-value></el-switch>
            </el-form-item>
            <el-form-item label="活动性质" prop="type">
              <el-checkbox-group v-model="formData.type">
                <el-checkbox label="美食/餐厅线上活动" name="type" value="1"></el-checkbox>
                <el-checkbox label="地推活动" name="type"></el-checkbox>
                <el-checkbox label="线下主题活动" name="type"></el-checkbox>
                <el-checkbox label="单纯品牌曝光" name="type"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item label="特殊资源" prop="resource">
              <el-radio-group v-model="formData.resource">
                <el-radio label="线上品牌商赞助"></el-radio>
                <el-radio label="线下场地免费"></el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
        </div>
        <p>dd</p>
        <p>dd</p>
        <p>dd</p>
        <span class="scroll-top"  @click="scrollToTop">
                <el-popover
                    placement="top-start"
                    width="200"
                    trigger="hover"
                    content="点击返回最上，向上滚动展示head—bar">
                  <span slot="reference" >
                    <i class="el-icon-upload2"></i>
                  </span>
              </el-popover>

        </span>
      </div>
    </div>
  </div>
</template>

<script>
import bus from '../../common/bus';
export default {
  name: "index",
  data(){
    return{
      loaded: false,
      rules: {
        posint:[
          { required: true, message: '请输入整数', trigger: 'blur' },
          { validator: this.validateNumber, trigger: 'blur' }
        ]
      },
      itemData: {
        basic: {
          name: 'name',
          number: -1,
          region: '',
          delivery: 0,
          type: [],
          resource: [],
        }
      },
      remark: {}
    }
  },
  beforeMount() {
  },
  mounted() {
    const myDiv = this.$refs.tabItemBox;
    myDiv.addEventListener('wheel', this.handleWheel);
  },
  beforeDestroy() {
    const myDiv = this.$refs.tabItemBox;
    myDiv.removeEventListener('wheel', this.handleWheel);
  },
  created() {
    // this.itemData = this.$store.state.itemData
    this.remark = this.itemData.remark
    // this.basic = this.itemData.basic
    this.formData = this.itemData.basic
    this.loaded = true

  },
  methods:{




    /*================头部操作、统一放在这里==============*/
    //搜索按钮
    headSearchFunc(){

    },
    //通用备注保存
    async saveRemark(){
      let param = {
        action : 'update_method',
        data: {
          "remark": this.itemData.remark
        },
        project: this.$route.query.project
      }
      let { data:res } = await this.axios.post(this.$settings.HOST + '/gui_zhen_action',param)
      if(res.status == 200){
        this.$message.success('update success')
      }else {
        this.$message.error(\`${res.info}\`)
      }
    },
    //头部添加
    headAddFunc(){

    },
    /*头部保存*/
    //请求预检校验 + 请求正式发送
    async headSaveFunc(){
      let validate = true
      this.$refs.formData.validate(res=>{
        console.log(res)
        validate = res
      })
      console.log(this.itemData)
      if(this.itemData.version >= 0 && this.itemData.version){
      }else {
        this.$message.warning('请输入正确版本号')
        return
      }
      if(validate){
        this.$message.success('校验通过')
      }else {
        this.$message.warning('校验不通过')
        return
      }
      console.log(this.itemData)

      this.headSavePost()
    },
      async headSavePost(){
        let param = {
          action : 'update_method',
          data: this.itemData,
          project: this.$route.query.project
        }
        let { data:res } = await this.axios.post(this.$settings.HOST + '/gui_zhen_action',param)
        if(res.status == 200){
          this.$message.success('update success')
          this.tableList = res.data
          this.emitInitPage()
        }else {
          this.$message.error(\`${res.info}\`)
        }
      },



    /*============= 校验规则================*/
    //大于-1
    validateNumber(rule, value, callback) {
      const number = parseInt(value);
      if (isNaN(number) || number < 0) {
        callback(new Error('请输入大于-1的整数'));
      } else {
        callback();
      }
    },

    /*================通用事件,非特殊情况不用处理==============*/
    //监听滚动事件
    handleWheel(event) {
      //触发父级head bar
      this.emitHandleWheel(event)

      const tabItemBox = this.$refs.tabItemBox;
      if (event.deltaY > 0) {
        if(tabItemBox) tabItemBox.style.height = 'calc(100vh - 180px)';

      } else {
        tabItemBox.style.height = 'calc(100vh - 245px)';
      }
    },
    //通过event bus来控制主要框架的行为
    //切换tab 、重绘页面 、重载页面
    emitChangeTab(){
      bus.$emit('change-tab', {tabIndex: 'tab1'});
    },
    emitReloadPage(){
      bus.$emit('reload-page', {tabIndex: 'tab0'});
    },
    emitInitPage(){
      bus.$emit('init-page', 'msg');
    },
    emitHandleWheel(event){
      bus.$emit('handle-wheel', {event:event});
    },


    //滚动置顶通用操作
    scrollToTop() {
      this.$refs.tabItemBox.scrollIntoView({ behavior: 'smooth', block: 'start' });
      this.handleWheel({deltaY:-1}) //模拟向上滚
    },

  }

}
</script>

<style scoped>
.tab-item-box{
  height: calc(100vh - 245px);
}

.tab-item-head{
  position: sticky;
  top: 0;
  min-height: 30px;
  display: flex;
  justify-content: space-between;
  margin: 0 0 10px 0;
  /*background-color: rgba(0, 255, 149, 0.1);*/
  box-shadow: 0px 10px 10px white;
  z-index: 1000;
  background-color: rgba(255, 255, 255, 0.8);
}
.tab-item-left{
  display: flex;
  flex-wrap: nowrap;
  align-items: flex-start;
}
.remark-search-input{
  margin-right: 10px;
  width: 200px;
}
.el-textarea__inner{
  height: 36px!important;
}
.tab-item-right{

}
.tab-item-body{
  position: relative;
  /*background-color: #409EFF;*/
  /*height: 150vh;*/
}
.main-body-content{
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center
}

/*模块通用操作*/
.scroll-top{
  padding: 6px 8px;
  height: 20px;
  width: 20px;
  line-height: 20px;
  border-radius: 5px;
  background-color: #f2f5f6;
  box-shadow: 0 0 3px 2px rgba(25,137,250, .1);
  text-align: center;
  color: #1989fa;
  position: sticky;
  left: 100%;
  bottom: 4px;
  border: 1px solid #cae4fd;
  opacity: 0.9;
}
.scroll-top:hover{
  cursor: pointer;
}
</style>
`
}












